package com.haoran.dwz.listener;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.haoran.dwz.config.util.NodeProperties;
import com.orbitz.consul.Consul;

public class ConsulRegisterListener implements ApplicationListener<ContextRefreshedEvent> {

	/**
	 * Application入口类中增加
	 * <pre>
	 * 
	 * 	public static void main(String[] args){
	 * 		SpringApplication sa = new SpringApplication(DwzConsoleApplication.class);
	 *		sa.addListeners(new ConsulRegisterListener());
	 *		sa.run(args);
	 * 	}
	 * 
	 * </pre>
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		ApplicationContext applicationContext = event.getApplicationContext();
		Consul consul = applicationContext.getBean(Consul.class);
		NodeProperties consulProperties = applicationContext.getBean(NodeProperties.class);
		int port = consulProperties.getServicePort();
		int interval = consulProperties.getHealthInterval();
		String healthUrl = consulProperties.getHealthUrl();
		URL http = null;
		try {
			http = URI.create(healthUrl).toURL();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		String name = consulProperties.getServiceName();
		String tags = consulProperties.getServiceTag();
		String id = name;
		consul.agentClient().register(port, http, interval, name, id, tags);
	}

}
